package com.wechat.order.aspect;

import com.wechat.order.constant.CookieConstant;
import com.wechat.order.constant.RedisConstant;
import com.wechat.order.exception.SellerAuthorizeException;
import com.wechat.order.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.protocol.RequestContent;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 正版微信扫码登陆aop拦截效验登陆
 * Created by zzy on 2017/12/21.
 */
@Aspect
/*@Component*/
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Pointcut("execution(public * com.wechat.order.controller.SellerController.Sell*.*(..))"+
    "&& !execution(public * com.wechat.order.controller.SellerController.SellerUserController.*(..))")
    public void verify(){}

    @Before("verify()")
    public void doVerify(){
        ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request= attributes.getRequest();
        //查询cookie
        Cookie cookie= CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie==null){
            log.warn("[登陆效验] cookie 取不到值");
            throw new SellerAuthorizeException();
        }
        //去redis查询
        String tokeValue=stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        if(StringUtils.isEmpty(tokeValue)){
            log.warn("[登陆效验] 找不到redis");
            throw new SellerAuthorizeException();
        }
    }
}
